<?php

namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\InsuranceInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/7/17 3:07
 */
class InsuranceRepository extends Repository implements InsuranceInterface
{
    protected $rules = [
        'created' => [
            'uid' => 'required|integer',
            'wish_id' => 'required|integer',
            'service_id' => 'required|integer'
        ]
    ];

    protected $messages = [
        'uid.required'       => "用户 ID 不能为空",
        'uid.integer'        => "用户 ID 必须是整数",
        'wish_id.required'   => "志愿 ID 不能为空",
        'wish_id.integer'    => "志愿 ID 必须是整数",
        'service_id.required'=> "所选服务不能为空",
        'service_id.integer' => "所选服务不合法"
    ];

    protected function modelName()
    {
        return 'App\Model\Insurance';
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');
        if ($this->model->where('uid', $data['uid'])->where('wish_id', $data['wish_id'])->first()) {
            throw new ValidateException('你已购买过保险');
        }

        return $this->save($data);
    }

    public function lists($limit, $page)
    {
        $total = $this->model->count();

        $list = $this->model->orderBy('uid', 'desc')->simplePaginate($limit, ['*'], 'page', $page);

        return $this->simplePaginate('list', $list->items(), $total);
    }

    public function detail($id)
    {
        return $this->find($id);
    }

    public function indemnity($uid, $id)
    {
        // TODO 理赔记录表

        return $this->model->where('id', $id)->update(['status' => 3]);
    }
}